<template>
  <div class="app-container">
    <nabars index="8"></nabars>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
      class="frominfo"
    >
      <!-- 搜索栏部分 -->
      <div class="from-item">
        <el-form-item label="参数名" prop="variableName">
          <el-input
            v-model="queryParams.variableName"
            @keyup.enter.native="handleQuery"
            placeholder="请输入参数名"
            clearable
          />
        </el-form-item>
        <el-form-item label="变量类型" prop="variableType">
          <el-select
            placeholder="请选择类型"
            v-model="queryParams.variableType"
          >
            <el-option
              v-for="dict in dict.type.sys_variable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
          <el-button
            class="blue-button"
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >查询</el-button
          >
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </div>
    </el-form>
    <!-- 导出按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          class="blue-button"
          @click="handleAdd"
          plain
          icon="el-icon-plus"
          size="mini"
          style="
            background-color: rgb(0, 120, 251);
            color: rgb(255, 255, 255);
            border-color: rgb(0, 120, 251);
          "
          >新增</el-button
        >
      </el-col>
    </el-row>
    <el-table
      v-loading="loading"
      :data="dataList"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ background: '#fcfcfd', color: '#000' }"
      :border="false"
    >
      <el-table-column label="变量名" align="center" prop="variableName" />
      <el-table-column label="变量值" align="center" prop="variableValue" />
      <el-table-column label="变量类型" align="center" prop="variableType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_variable"
            :value="scope.row.variableType"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="创建人" align="center" prop="createBy" /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:dict:edit']"
            >修改</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="del(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 -->
    <el-dialog
      :title="title"
      :visible.sync="isShow"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="变量名称">
          <el-select
            v-model="formData.variableId"
            placeholder="请下拉选择"
            clearable
            :style="{ width: '90%', maiginLeft: '100px' }"
            @change="handleChange"
          >
            <el-option
              v-for="(item, index) in canUseParams"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="变量值" prop="variableName">
          <el-input
            v-model="formData.variableValue"
            placeholder="请输入变量值"
            :disabled="formData.variableType == 1 ? false : true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="上传"
          prop="defaultValue"
          required
          v-if="formData.variableType == 3 || formData.variableType == 4"
        >
          <el-upload
            class="upload-demo"
            ref="upload"
            :headers="headers"
            :action="uploadUrl"
            :disabled="isUploading"
            :before-upload="handleBeforeUpload"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
          >
            <el-button size="small" type="primary" icon="el-icon-upload2">{{
              formData.variableType == "2"
                ? "上传"
                : formData.variableType == "3"
                ? "上传图片"
                : "上传文件"
            }}</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel2">取消</el-button>
          <el-button type="primary" @click="confirm"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      :title="title"
      :visible.sync="isEditShow"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="formEditData" label-width="80px">
        <el-form-item label="变量名" prop="variableName">
          <el-input
            v-model="formEditData.variableName"
            placeholder="请输入变量值"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="变量值" prop="variableValue">
          <el-input
            v-model="formEditData.variableValue"
            placeholder="请输入变量值"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel2">取消</el-button>
          <el-button type="primary" @click="confirm2"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { getToken } from "@/utils/auth";
import nabars from "../components/nabar.vue";
export default {
  dicts: ["sys_variable"],
  components: {
    nabars,
  },
  data() {
    return {
      idx: 0,
      name: [],
      loadings: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      dataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isShow: false,
      isEditShow: false,
      isEditor: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        dictType: "group_label",
        dictLabel: null,
        dictValue: null,
        dictSort: null,
        remark: null,
      },
      formData: {
        variableId: null,
        variableValue: null,
        variableType: "",
      },
      formEditData: {
        variableId: "",
        variableName: "",
        variableValue: "",
      },
      // 表单校验
      rules: {
        // variableName: [
        //   { required: true, message: "参数名不能为空", trigger: "blur" },
        // ],
        // variableType: [
        //   { required: true, message: "变量类型不能为空", trigger: "blur" },
        // ],
      },
      fileSize: 5,
      fileType: ["png", "jpg", "jpeg"],
      headers: { Authorization: "Bearer " + getToken() },
      isUploading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      canUseParams: [],
    };
  },
  created() {
    this.getList();
    getUseParams().then((res) => {
      this.canUseParams = res.data.map((item) => {
        return {
          label: item.variableName + "-" + this.handleType(item.variableType),
          value: item.variableId,
        };
      });
    });
  },
  methods: {
    handleType(num) {
      switch (num) {
        case 0:
          return "其他";
        case 1:
          return "文字";
        case 2:
          return "链接";
        case 3:
          return "图片";
        case 4:
          return "文件";
      }
    },
    handleChange(val) {
      if (val) {
        getParamsType(val).then((res) => {
          this.formData.variableType = res.data.variableType;
          // alert(this.formData.variableType);
        });
      }
    },
    cancel2() {
      this.isShow = false;
      this.isEditShow = false;
    },
    confirm() {
      addList(this.formData).then((res) => {
        if (res.code == 200) {
          this.$message.success("新增成功");
          this.getList();
          this.isShow = false;
          this.formData.variableId = "";
          this.formData.variableName = "";
          this.formData.variableValue = "";
        }
      });
    },
    confirm2() {
      updateList(this.formEditData).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.getList();
          this.isEditShow = false;
        }
      });
    },
    /** 查询微信好友信息列表 */
    async getList() {
      this.loading = true;
      getVariableList(this.queryParams).then((res) => {
        if (res["code"] == 200) {
          const dt = res["data"];
          this.total = dt["total"];
          this.dataList = dt["rows"];
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        variableName: null,
        defaultValue: null,
        variableType: null,
        variableDescribe: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.variableId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.open = true;
      this.isShow = true;
      this.title = "添加信息";
    },
    del(row) {
      this.$confirm(
        "是否确认删除变量名称为" + row.variableName + "的数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        delInfo(row.variableId).then((res) => {
          if (res.code == 200) {
            this.getList();
            this.$message.success("删除成功");
          }
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isEditShow = true;
      this.title = "修改信息";
      // this.formEidtData = {
      //   variableType: row.variableType,
      //   variableId: row.id,
      //   variableValue: row.variableValue,
      // };
      this.formEditData.variableId = row.variableId;
      this.formEditData.variableName = row.variableName;
      this.formEditData.variableValue = row.variableValue;
    },
    /** 提交按钮 */
    submitForm() {
      // this.$refs["form"].validate((valid) => {
      //   if (valid) {
      //     if (this.form.variableId != undefined) {
      //       updateList(this.form).then((response) => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addList(this.form).then((response) => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.variableId || this.ids;
      this.$modal
        .confirm("是否确认删除所选数据项？")
        .then(function () {
          return delInfo(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      console.log(this.form);
      if (this.form.variableType == "3") {
        let isImg = false;
        if (this.fileType.length) {
          let fileExtension = "";
          if (file.name.lastIndexOf(".") > -1) {
            fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
          }
          isImg = this.fileType.some((type) => {
            if (file.type.indexOf(type) > -1) return true;
            if (fileExtension && fileExtension.indexOf(type) > -1) return true;
            return false;
          });
        } else {
          isImg = file.type.indexOf("image") > -1;
        }

        if (!isImg) {
          this.$modal.msgError(
            `文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`
          );
          return false;
        }
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传图片，请稍候...");
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      // console.log(response);
      // this.$modal.closeLoading();
      // // this.form.defaultValue = response.url;
      // this.isUploading = false;
      // this.$refs.upload.clearFiles();
      this.formData.variableValue = response.url;
      // console.log(this.formData.defaultValue);
    },
  },
};
//获取列表
export function getVariableList(query) {
  return request({
    url: "/arbit/wcvariable_user/page",
    method: "get",
    params: query,
  });
}
//新增
export function addList(query) {
  return request({
    url: "/arbit/wcvariable_user/add",
    method: "post",
    data: query,
  });
}
//详情
export function getInfo(id) {
  return request({
    url: "/label/relevance/" + id,
    method: "get",
  });
}
//修改
export function updateList(query) {
  return request({
    url: "/arbit/wcvariable_user/edit",
    method: "PUT",
    data: query,
  });
}
//删除
export function delInfo(id) {
  return request({
    url: "/arbit/wcvariable_user/delete/" + id,
    method: "DELETE",
  });
}
// 助手-查询当前用户可以新增的变量类型
export function getUseParams() {
  return request({
    url: "/arbit/wcvariable/getCanAddVariable",
    method: "get",
  });
}
// 根据id查询参数类型
export function getParamsType(id) {
  return request({
    url: "/arbit/wcvariable/queryWcVariableById/" + id,
    method: "get",
  });
}
</script>
<style lang="scss">
.app-container {
  background-color: #f6f9fb;
}
.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;

  .from-item {
    display: flex;
    flex-wrap: wrap;
    width: 85%;
  }

  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}
.add-upload {
  display: flex;
  width: 400px;
  border-radius: 5px;
  border: 1px solid #dcdfe6;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  margin-left: 15px;
  margin-bottom: 20px;
}
::v-deep {
  .el-form-item--medium .el-form-item__label {
    width: 120px !important;
  }
}
</style>
